SMS.controller('AppController',
function AppController($scope, $rootScope, $document, $location, utils, globals, model, notifications, player) {
    $rootScope.settings = globals.settings;
    $rootScope.mediaElement = [];
    $rootScope.queue = [];
    $rootScope.playingMediaElement;
    $rootScope.mediaFolders = [];
    $rootScope.selectedPlaylist = "";
    $rootScope.selectedAutoPlaylist = "";
    $rootScope.selectedMediaFolder = "";
    $rootScope.unity;

    $rootScope.$watch("selectedMediaFolder", function (newValue, oldValue)
    {
        if (newValue !== oldValue)
        {
            if (typeof newValue != 'undefined' && newValue != null)
            {
                utils.setValue('mediaFolders', angular.toJson(newValue), true);
            }
            else
            {
                utils.setValue('mediaFolders', null, true);
            }
        }
    });

    // Reads cookies and sets globals.settings values
    $scope.loadSettings = function () {
        if (utils.getValue('Settings')) {
            $.each(utils.getValue('Settings'), function (k, v) {
                if (v == 'false') { v = false; }
                if (v == 'true') { v = true; }
                globals.settings[k] = v;
            });
        }
        if (utils.getValue("SavedCollections")) { globals.SavedCollections = utils.getValue("SavedCollections").split(","); }
        if (globals.settings.Debug) { console.log('Settings: ' + JSON.stringify(globals.settings, null, 2)); }
    }
    $scope.toggleSetting = function (setting) {
        var id = setting;
        if (globals.settings[id]) {
            globals.settings[id] = false;
        } else {
            globals.settings[id] = true;
        }
        notifications.updateMessage(setting + ' : ' + globals.settings[id], true);
    }

    $.ajaxSetup({
        'beforeSend': function () {
            $("#loading").show();
        },
        'complete': function () {
            $("#loading").hide();
        }
    });


    $("a.coverArtFancy").live("click", function () {
        $("a.coverArtFancy").fancybox({
            beforeShow: function () {
            },
            afterLoad: function () {
            },
            hideOnContentClick: true,
            type: 'image',
            openEffect: 'none',
            closeEffect: 'none'
        });
    });

    var submenu_active = false;
    $('div.submenu').mouseenter(function () {
        submenu_active = true;
    });
    $('div.submenu').mouseleave(function () {
        submenu_active = false;
        $('div.submenu').hide();
        //setTimeout(function () { if (submenu_active == false) $('div.submenu').stop().fadeOut(); }, 400);
    });
    $scope.toggleSubmenu = function (menu, pl, pos, margin)
    {
        var submenu = $(menu);
        if (submenu.css('display') !== 'none') {
            submenu.fadeOut();
        } else {
            var el = $(pl);
            off = el.offset();
            width = el.width();
            height = el.height();
            switch (pos) {
                case 'right':
                    //show the menu to the right of placeholder
                    submenu.css({ "left": (off.left + margin) + "px", "top": (off.top) + "px" }).fadeIn(400);
                    break;
                case 'left':
                    //show the menu to the right of placeholder
                    submenu.css({ "left": (off.left - margin) + "px", "top": (off.top) + "px" }).fadeIn(400);
                    break;
            }
            setTimeout(function () { if (submenu_active == false) $('div.submenu').stop().fadeOut(); }, 10000);
        }
    }

    $("a.coverArtFancy").fancybox({
        beforeShow: function () {
        },
        afterLoad: function () {
        },
        hideOnContentClick: true,
        type: 'image',
        openEffect: 'none',
        closeEffect: 'none'
    });

    $('#audiocontainer .scrubber').mouseover(function (e) {
        $('.audiojs .scrubber').stop().animate({ height: '8px' });
    });
    $('#audiocontainer .scrubber').mouseout(function (e) {
        $('.audiojs .scrubber').stop().animate({ height: '4px' });
    });

    $('.message').live('click', function () { $(this).remove(); });

    // JQuery UI Sortable - Drag and drop sorting
    var fixHelper = function (e, ui) {
        ui.children().each(function () {
            $(this).width($(this).width());
        });
        return ui;
    };
    $("#QueuePreview ul.mediaelementlist").sortable({
        helper: fixHelper
    });

    // Sway.fm Unity Plugin
    $rootScope.unity = UnityMusicShim();
    $rootScope.unity.setSupports({
        playpause: true,
        next: true,
        previous: true
    });
    $rootScope.unity.setCallbackObject({
        pause: function () {
            if (globals.settings.Debug) { console.log("Unity: Recieved playpause command"); }
            player.playPause();
        },
        next: function () {
            if (globals.settings.Debug) { console.log("Unity: Recieved next command"); }
            $rootScope.nextTrack();
        },
        previous: function () {
            if (globals.settings.Debug) { console.log("Unity: Recieved previous command"); }
            $rootScope.previousTrack();
        }
    });

    // JQuery Layout Plugin
    function resizePageLayout() {
        var pageLayout = $("body").data("layout");
        if (pageLayout) pageLayout.resizeAll();
    };

    $scope.layoutThreeColumns = {
        east__size: .45,
        east__minSize: 400,
        east__maxSize: .5, // 50% of layout width
        east__initClosed: false,
        east__initHidden: false,
        center__minWidth: .35,
        center__initClosed: false,
        center__initHidden: false,
        west__size: .2,
        west__minSize: 200,
        west__initClosed: false,
        west__initHidden: false,
        showDebugMessages: true
    };

    $scope.layoutTwoColumns = {
        center__size: .8,
        center__minSize: 400,
        center__maxSize: .5, // 50% of layout width
        center__initClosed: false,
        center__initHidden: false,
        west__size: .2,
        west__minSize: 200,
        west__initClosed: false,
        west__initHidden: false,
        showDebugMessages: true
    };

    // Global Functions
    window.onbeforeunload = function ()
    {
        if ($rootScope.queue.length > 0)
        {
            return "You're about to end your session, are you sure?";
        }
    };

    $document.keydown(function (e) {
        $scope.scrollToIndex(e);
    });
    $scope.scrollToIndex = function (e)
    {
        var source = e.target.id;
        if (source != 'Search' && source != 'Source' && source != 'Description' && source != 'AutoPlaylists') {
            var unicode = e.charCode ? e.charCode : e.keyCode;
            if (globals.settings.Debug) { console.log('Keycode Triggered: ' + unicode); }
            if (unicode >= 65 && unicode <= 90 && $('#tabLibrary').is(':visible')) { // a-z
                var key = utils.findKeyForCode(unicode);
                if (key == 'x' || key == 'y' || key == 'z') {
                    key = 'x-z';
                }
                var el = '#' + key.toUpperCase();
                if ($(el).length > 0) {
                    $('#SMSIndexes').stop().scrollTo(el, 400);
                }
            } else if (unicode == 39 || unicode == 176) { // right arrow
                $rootScope.nextTrack();
            } else if (unicode == 37 || unicode == 177) { // back arrow
                $rootScope.previousTrack();
            } else if (unicode == 32 || unicode == 179 || unicode == 0179) { // spacebar
                player.playPause();
                return false;
            } else if (unicode == 36 && $('#tabLibrary').is(':visible')) { // home
                $('#SMSIndexes').stop().scrollTo('#MediaFolders', 400);
            }
            if (unicode == 189) { // dash - volume down
                var volume = utils.getValue('Volume') ? parseFloat(utils.getValue('Volume')) : 1;
                if (volume <= 1 && volume > 0 && source == '') {
                    volume += -.1;
                    $(player1).jPlayer({
                        volume: volume
                    });
                    utils.setValue('Volume', volume, true);
                }
            }
            if (unicode == 187) { // equals - volume up
                var volume = utils.getValue('Volume') ? parseFloat(utils.getValue('Volume')) : 1;
                if (volume < 1 && volume >= 0 && source == '') {
                    volume += .1;
                    $(player1).jPlayer({
                        volume: volume
                    });
                    utils.setValue('Volume', volume, true);
                }
            }
        }
        return true;
    };
    $scope.scrollToIndexName = function (index) {
        var el = '#' + index;
        if ($(el).length > 0) {
            $('#SMSIndexes').stop().scrollTo(el, 400);
        }
    };
    $scope.scrollToTop = function () {
        $('#IndexElements').stop().scrollTo('#auto', 400);
    }
    $scope.selectAll = function () {
        angular.forEach($rootScope.mediaElement, function (item, key) {
            $scope.selectedMediaElements.push(item);
            item.selected = true;
        });
    }
    $scope.selectNone = function () {
        angular.forEach($rootScope.mediaElement, function (item, key) {
            $scope.selectedMediaElements = [];
            item.selected = false;
        });
    }
    $scope.isActive = function (route) {
        return route === $location.path();
    };
    $scope.getMediaFolders = function () {
        $.ajax({
            url: globals.BaseURL() + '/getMediaFolders.view?' + globals.BaseParams(),
            method: 'GET',
            dataType: globals.settings.Protocol,
            timeout: globals.settings.Timeout,
            success: function (data) {
                if (data["sms-response"].mediaFolders.mediaFolder !== undefined)
                {
                    var folders = [];
                    if (data["sms-response"].mediaFolders.mediaFolder.length > 0)
                    {
                        folders = data["sms-response"].mediaFolders.mediaFolder;
                    }
                    else
                    {
                        folders[0] = data["sms-response"].mediaFolders.mediaFolder;
                    }

                    $rootScope.mediaFolders = folders;
                    if (utils.getValue('mediaFolders'))
                    {
                        var folder = angular.fromJson(utils.getValue('mediaFolders'));
                        var i = 0, index = "";
                        angular.forEach($rootScope.mediaFolders, function (item)
                        {
                            if (item.id == folder.id)
                            {
                                index = i;
                            }
                            i++;
                        });
                        $rootScope.selectedMediaFolder = $rootScope.mediaFolders[index];
                    }
                    $scope.$apply();
                }
            }
        });
    }
    $scope.download = function (id) {
        $.ajax({
            url: globals.BaseURL() + '/getUser.view?' + globals.BaseParams() + '&username=' + globals.settings.Username,
            method: 'GET',
            dataType: globals.settings.Protocol,
            timeout: globals.settings.Timeout,
            success: function (data) {
                if (data["sms-response"].user.downloadRole == true) {
                    $window.location.href = globals.BaseURL() + '/download.view?' + globals.BaseParams() + '&id=' + id;
                } else {
                    notifications.updateMessage('You do not have permission to Download', true);
                }
            }
        });
    };
    $scope.addMediaElementToQueue = function (data) {
        $rootScope.queue.push(data);
    }
    $scope.queueRemoveSelected = function (data, event) {
        angular.forEach($scope.selectedMediaElements, function (item, key) {
            var index = $rootScope.queue.indexOf(item);
            if (index > -1) {
                $rootScope.queue.splice(index, 1);
            }
        });
    }
    $scope.queueEmpty = function () {
        $rootScope.queue = [];
    }
    $scope.queueTotal = function () {
        var total = 0;
        ko.utils.arrayForEach(self.queue(), function (item) {
            total += parseInt(item.duration());
        });
        if (self.queue().length > 0) {
            return self.queue().length + ' Track(s), ' + utils.secondsToTime(total) + ' total time';
        } else {
            return '0 Track(s), 00:00:00 total time';
        }
    }
    $scope.queueShuffle = function () {
        $rootScope.queue.sort(function () { return 0.5 - Math.random() });
    }
    $scope.selectedMediaElements = [];
    $scope.selectMediaElement = function (data) {
        var i = $scope.selectedMediaElements.indexOf(data);
        if (i >= 0) {
            $scope.selectedMediaElements.splice(i, 1);
            data.selected = false;
        } else {
            $scope.selectedMediaElements.push(data);
            data.selected = true;
        }
    }
    // Tests connection to SMS server
    $scope.ping = function () {
        $.ajax({
            url: globals.BaseURL() + '/ping.view?' + globals.BaseParams(),
            method: 'GET',
            dataType: globals.settings.Protocol,
            timeout: globals.settings.Timeout,
            error: function () {
                alert('Unable to connect to SMS server');
            }
        });
    }
    /* Launch on Startup */
    $scope.loadSettings();
    if (globals.settings.Server != '' && globals.settings.Username != '' && globals.settings.Password != '') {
        $scope.getMediaFolders();
        if (globals.settings.SaveTrackPosition) {
            player.loadTrackPosition();
            player.startSaveTrackPosition();
        }
    }
    /* End Startup */
});